/*
 * @Author: Swance
 * @Date: 2024-02-29
 * @Description: 操作对象（封装WebSocket通信的最小粒度）
 */

import { BoardSyncEvent } from '@/utils/Const.ts';

class Action {
  type: string;
  oldElements: Array<any>;
  newElements: Array<any>;
  private isNewAction: boolean;

  constructor(
    type: string,
    flag: boolean,
    oldElements?: Array<any>,
    newElements?: Array<any>,
  ) {
    this.type = type;
    this.oldElements = oldElements || [];
    this.newElements = newElements || [];
    this.isNewAction = flag;
  }

  // 转换为逆操作
  convert() {
    if (this.type === BoardSyncEvent.ADD) {
      this.type = BoardSyncEvent.REMOVE;
      const tmp = this.newElements;
      this.newElements = this.oldElements;
      this.oldElements = tmp;
    } else if (this.type === BoardSyncEvent.REMOVE) {
      this.type = BoardSyncEvent.ADD;
      const tmp = this.oldElements;
      this.oldElements = this.newElements;
      this.newElements = tmp;
      // 修改的逆操作即把新旧状态交换（undo时删除新状态，添加旧状态；redo时删除旧状态，删除新状态）
    } else if (this.type === BoardSyncEvent.UPDATE) {
      const tmp = this.newElements;
      this.newElements = this.oldElements;
      this.oldElements = tmp;
    } else if (this.type === BoardSyncEvent.UP) {
      this.type = BoardSyncEvent.DOWN;
    } else if (this.type === BoardSyncEvent.DOWN) {
      this.type = BoardSyncEvent.UP;
    }
  }

  // 设置新旧变更标识
  setNewFlag(params: boolean) {
    this.isNewAction = params;
  }

  getNewFlag(): boolean {
    return this.isNewAction;
  }
}
export default Action;
